package com.mango.module.base.job;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.mango.module.base.Constant;
import com.mango.module.base.Constant.PushType;
import com.mango.module.base.config.PipelineConfig;
import com.mango.module.base.config.SpringContextUtils;
import com.mango.module.base.dto.PushData;
import com.mango.module.ldap.LdapUtil;
import com.mango.module.ldap.domain.PersonDO;
import com.mango.module.ldap.service.IPersonService;
import com.mango.module.util.QueueUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * ldap定时获取用户
 * @author Mango-Lab
 * @Date 2021年4月8日
 */

public class LdapUserTask {
	
	/**
	 * 启动
	 */
	public static void start() {
		long delay= 60;
		long period= 24 * 60 * 60;
		System.out.println("ldap定时获取用户，延迟"+delay+"秒启动，周期："+period+"秒");
		Timer timer = new Timer();
		timer.schedule(new UserTask(), delay * 1000, period * 1000);
	}
	public static void main(String[] args) {
		start();
	}
}

@Slf4j
class UserTask extends TimerTask {

	@Override
	public void run() {
		log.info("==========================同步用户 START=============================》");
		IPersonService personService = SpringContextUtils.getBean(IPersonService.class);
		QueueUtils queueUtils = SpringContextUtils.getBean("queueUtils", QueueUtils.class);
		PipelineConfig pConfig=SpringContextUtils.getBean(PipelineConfig.class);
		String basedn = pConfig.getLdapbase();//"dc=njupt,dc=edu,dc=cn";  // basedn
		List<PersonDO> list = LdapUtil.readLdap(basedn);
		if (list == null || list.size() == 0) {
			log.info("没有要同步的数据！");
			return;
		}
		int len = list.size();
		PersonDO temp = null;
		PersonDO pDO = null;
		for (int i = 0; i < len; i++) {
			pDO = list.get(i);
			temp = personService.getPersonByUid(pDO.getUserId());
			if (temp == null) {
				// 新增
				personService.addUser(pDO);
				log.info("add-user:{}", JSON.toJSONString(pDO));
				queueUtils.send(Constant.MQ_QUEUE_KEY, JSON.toJSONString(new PushData(PushType.USER_ADD,pDO)));
				continue;
			}

			if (StringUtils.isNotEmpty(pDO.getUserPassword()) && pDO.getUserPassword().equals(temp.getUserPassword())) {
				continue;
			}
			personService.updateUser(pDO);
			log.info("update-user:{}", JSON.toJSONString(pDO));
			queueUtils.send(Constant.MQ_QUEUE_KEY, JSON.toJSONString(new PushData(PushType.USER_UPDATE,pDO)));

			// 删除人员无法判断
		}
		log.info("《=========================同步用户END==============================");
	}
}